package com.applet.applet_shangcheng.controller;

import com.alibaba.fastjson.JSONObject;
import com.applet.applet_shangcheng.service.ImageService;
import com.applet.applet_shangcheng.utlis.AppletUtil;
import com.mysql.cj.xdevapi.JsonArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ImageFiles")
@CrossOrigin
@Api(value="图片上传")
public class ImageFiles {
    private static final Logger Logger = LoggerFactory.getLogger(ImageFiles.class);

    @Value("${applet.path.upload}")
    private String uploadPath;
    @Value("${applet.path.domain}")
    private String domain;

    @Autowired
    private ImageService imageService;
    @ApiOperation(value="_图片上传")
    @PostMapping("/upload")
    @ResponseBody
    public String uploadImage(MultipartFile image){
        if (image==null){
            return "您还没有选择图片!";
        }
        String fileName = image.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isEmpty(suffix)){
                return "文件格式不正确!";
        }
        //随机字符串
        fileName= AppletUtil.generateUUID()+suffix;
        File dest =new File(uploadPath+"/"+fileName);
        try {
            //存储文件
            image.transferTo(dest);
        } catch (IOException e) {
            Logger.error("上传文件失败:"+e.getMessage());
            throw new RuntimeException("上传文件失败"+e);
        }
        //更新路径(web路径)
        String imageUrl=domain + "/ImageFiles/image/"+fileName;
        imageService.insertImage(fileName,imageUrl);
        System.out.println(imageUrl);
        return imageUrl;
    }
    @PostMapping("/uploadImageS")
    @ResponseBody
    @ApiOperation(value="_图片列表上传")
    public String uploadImageS(@RequestParam("images")MultipartFile[] images){
        List<String> list = new ArrayList<>();
       // System.out.println(images.length);
        for (MultipartFile image : images) {
            if (image==null){
                return "您还没有选择图片!";
            }
            String fileName = image.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            if (StringUtils.isEmpty(suffix)){
                return "文件格式不正确!";
            }
            //随机字符串
            fileName= AppletUtil.generateUUID()+suffix;
            File dest =new File(uploadPath+"/"+fileName);
            try {
                //存储文件
                image.transferTo(dest);
            } catch (IOException e) {
                Logger.error("上传文件失败:"+e.getMessage());
                throw new RuntimeException("上传文件失败"+e);
            }
            //更新路径(web路径)
            String url=domain + "/ImageFiles/image/"+fileName;

            list.add(url);
            imageService.insertImage(fileName,url);
            return url;
        }
        String jsonString = list.toString();
       /* String jsonString = JSONObject.toJSONString(list);*/
        System.out.println(jsonString);
        return jsonString;
    }

    @GetMapping("/image/{fileName}")
    @ResponseBody
    @ApiOperation(value="_查询图片")
    public void getImage(@PathVariable("fileName") String fileName, HttpServletResponse response){
        //服务器路径
        fileName=uploadPath+"/"+fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
       // response.setContentType("image/"+suffix);
        response.setCharacterEncoding("UTF-8");
        response.setHeader(suffix,"text/html;charset=UTF-8");
        try (
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(fileName);
         ){
            byte[] buffer=new byte[1024];
            int b=0;
            while ((b=fis.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            Logger.error("读取失败"+e.getMessage());
        }
    }
}
